package com.angola.sms.update;

import android.os.Message;
import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

public class ZHIVersionResBody extends ResponseBody {
    private ResponseBody mResponseBody;
    private BufferedSource mBufferedSource;
    private ZHIVersionMsgHandler mZHIVersionMsgHandler;

    public ZHIVersionResBody(ResponseBody body, ZHIVersionProgressListener listener) {
        mResponseBody = body;
        if (mZHIVersionMsgHandler == null) {
            mZHIVersionMsgHandler = new ZHIVersionMsgHandler(listener);
        }
    }

    @Override
    public long contentLength() {
        return mResponseBody.contentLength();
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return mResponseBody.contentType();
    }

    @NotNull
    @Override
    public BufferedSource source() {
        if (mBufferedSource == null) {
            mBufferedSource = Okio.buffer(getDownloadSource(mResponseBody.source()));
        }
        return mBufferedSource;
    }

    private Source getDownloadSource(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(@NotNull Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;

                Log.d(ZHIVersionResBody.class.getSimpleName(), "read: " + totalBytesRead + ", totalLength: " + contentLength() + ", done: " + (totalBytesRead == contentLength()));

                Message msg = Message.obtain();
                msg.what = ZHIVersionMsgHandler.UPDATE;
                msg.obj = new ZHIVersionProgress(totalBytesRead, contentLength(), totalBytesRead == contentLength());
                mZHIVersionMsgHandler.sendMessage(msg);

                return bytesRead;
            }
        };
    }
}
